<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
      xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"
      layout:decorate="~{layout/base}">
<head>
    <title>农产品管理 - 暖心助农选品平台</title>
</head>
<body>
    <div layout:fragment="content">
        <div class="d-flex justify-content-between align-items-center mb-4">
            <h2>农产品管理</h2>
            <!-- <div>
                <a th:href="@{/admin/products/pending}" class="btn btn-warning me-2">待审核农产品</a>
                <a th:href="@{/admin/products/export}" class="btn btn-secondary">导出数据</a>
            </div> -->
        </div>

        <div class="card mb-4">
            <div class="card-body">
                <form th:action="@{/admin/products}" method="get" class="row g-3">
                    <div class="col-md-3">
                        <input type="text" class="form-control" name="keyword" th:value="${param.keyword}" placeholder="搜索农产品...">
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" name="category">
                            <option value="">所有类别</option>
                            <option value="vegetables" th:selected="${param.category == 'vegetables'}">蔬菜</option>
                            <option value="fruits" th:selected="${param.category == 'fruits'}">水果</option>
                            <option value="grains" th:selected="${param.category == 'grains'}">粮食</option>
                            <option value="others" th:selected="${param.category == 'others'}">其他</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <select class="form-select" name="status">
                            <option value="">所有状态</option>
                            <option value="approved" th:selected="${param.status == 'approved'}">已审核</option>
                            <option value="pending" th:selected="${param.status == 'pending'}">待审核</option>
                        </select>
                    </div>
                    <div class="col-md-2">
                        <button type="submit" class="btn btn-primary w-100">搜索</button>
                    </div>
                </form>
            </div>
        </div>

        <div th:if="${products.empty}" class="alert alert-info">
            没有找到符合条件的农产品。
        </div>

        <div th:unless="${products.empty}" class="table-responsive">
            <table class="table table-striped table-hover">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>图片</th>
                        <th>名称</th>
                        <th>类别</th>
                        <th>价格</th>
                        <th>库存</th>
                        <th>状态</th>
                        <th>农户</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr th:each="product : ${products}">
                        <td th:text="${product.id}">ID</td>
                        <td>
                            <img th:if="${product.image}" th:src="@{${product.image}}" 
                                 class="img-thumbnail" style="width: 50px;" alt="产品图片">
                            <img th:unless="${product.image}" th:src="@{/images/default-product.jpg}" 
                                 class="img-thumbnail" style="width: 50px;" alt="默认产品图片">
                        </td>
                        <td th:text="${product.name}">名称</td>
                        <td th:text="${product.category}">类别</td>
                        <td th:text="'￥' + ${product.price}">价格</td>
                        <td th:text="${product.stock}">库存</td>
                        <td>
                            <span class="badge" th:classappend="${product.approved ? 'bg-success' : 'bg-warning'}"
                                  th:text="${product.approved ? '已审核' : '待审核'}">状态</span>
                        </td>
                        <td th:text="${product.farmer.realName}">农户</td>
                        <td>
                            <div class="btn-group btn-group-sm">
                                <button th:if="${!product.approved}" class="btn btn-success approve-btn"
                                        th:data-product-id="${product.id}">通过</button>
                                <button class="btn btn-primary edit-btn"
                                        th:data-product-id="${product.id}"
                                        onclick="editProduct(this.getAttribute('data-product-id'))">编辑</button>
                                <button class="btn btn-danger delete-btn"
                                        th:data-product-id="${product.id}"
                                        th:data-product-name="${product.name}"
                                        onclick="deleteProduct(this.getAttribute('data-product-id'), this.getAttribute('data-product-name'))">删除</button>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>

        <!-- 编辑农产品模态框 -->
        <div class="modal fade" id="editProductModal" tabindex="-1" aria-labelledby="editProductModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title" id="editProductModalLabel">编辑农产品</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        <form id="editProductForm" class="needs-validation" novalidate>
                            <input type="hidden" id="editProductId">
                            <div class="mb-3">
                                <label for="editProductName" class="form-label">产品名称</label>
                                <input type="text" class="form-control" id="editProductName" required>
                                <div class="invalid-feedback">
                                    请输入产品名称
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="editProductDescription" class="form-label">产品描述</label>
                                <textarea class="form-control" id="editProductDescription" rows="3" required></textarea>
                                <div class="invalid-feedback">
                                    请输入产品描述
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="editProductCategory" class="form-label">类别</label>
                                <select class="form-select" id="editProductCategory" required>
                                    <option value="">请选择类别</option>
                                    <option value="vegetables">蔬菜</option>
                                    <option value="fruits">水果</option>
                                    <option value="grains">粮食</option>
                                    <option value="others">其他</option>
                                </select>
                                <div class="invalid-feedback">
                                    请选择产品类别
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="editProductPrice" class="form-label">价格</label>
                                <div class="input-group">
                                    <span class="input-group-text">￥</span>
                                    <input type="number" class="form-control" id="editProductPrice" 
                                           step="0.01" min="0" required>
                                    <div class="invalid-feedback">
                                        请输入有效的价格
                                    </div>
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="editProductStock" class="form-label">库存</label>
                                <input type="number" class="form-control" id="editProductStock" 
                                       min="0" required>
                                <div class="invalid-feedback">
                                    请输入有效的库存数量
                                </div>
                            </div>
                            <div class="mb-3">
                                <label for="editProductImage" class="form-label">产品图片</label>
                                <input type="file" class="form-control" id="editProductImage" 
                                       accept="image/*">
                                <div class="form-text">如果不上传新图片，将保留当前图片。</div>
                                <div id="currentProductImage" class="mt-2"></div>
                            </div>
                        </form>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="saveProductEdit()">保存</button>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <th:block layout:fragment="scripts">
        <script th:inline="javascript">
            // 定义一个变量来存储模态框实例
            let productModal;

            // 将函数定义移到全局作用域
            function editProduct(id) {
                console.log('Editing product with ID:', id);
                
                // 确保 Bootstrap 已加载
                if (typeof bootstrap === 'undefined') {
                    console.error('Bootstrap is not loaded!');
                    alert('页面加载错误，请刷新页面后重试');
                    return;
                }
                
                // 先重置表单
                $('#editProductForm').trigger('reset');
                $('#currentProductImage').empty();
                
                // 构建正确的URL
                const baseUrl = /*[[@{/admin/products}]]*/ '';
                const url = `${baseUrl}/${id}`;
                console.log('Fetching product data from:', url);
                
                $.ajax({
                    url: url,
                    type: 'GET',
                    dataType: 'json',
                    contentType: 'application/json',
                    success: function(response) {
                        console.log('Received response:', response);
                        
                        // 从响应中获取产品数据
                        const product = response;
                        
                        // 检查产品数据是否完整
                        if (!product || !product.id) {
                            console.error('Invalid product data received:', product);
                            alert('获取产品信息失败：数据不完整');
                            return;
                        }
                        
                        try {
                            // 填充表单数据
                            $('#editProductId').val(product.id);
                            $('#editProductName').val(product.name || '');
                            $('#editProductDescription').val(product.description || '');
                            $('#editProductCategory').val(product.category || '');
                            $('#editProductPrice').val(product.price || '0');
                            $('#editProductStock').val(product.stock || '0');
                            
                            console.log('Form data filled:', {
                                id: $('#editProductId').val(),
                                name: $('#editProductName').val(),
                                description: $('#editProductDescription').val(),
                                category: $('#editProductCategory').val(),
                                price: $('#editProductPrice').val(),
                                stock: $('#editProductStock').val()
                            });
                            
                            // 显示当前图片
                            if (product.image) {
                                var img = $('<img>').attr({
                                    'src': /*[[@{/}]]*/ '' + product.image,
                                    'class': 'img-thumbnail',
                                    'style': 'max-width: 200px;'
                                });
                                $('#currentProductImage').html(img);
                                console.log('Product image set:', product.image);
                            }
                        } catch (error) {
                            console.error('Error filling form data:', error);
                            alert('填充表单数据时发生错误：' + error.message);
                            return;
                        }
                        
                        // 显示模态框
                        const modalElement = document.getElementById('editProductModal');
                        if (!modalElement) {
                            console.error('Modal element not found');
                            alert('页面加载错误，请刷新页面后重试');
                            return;
                        }

                        if (!productModal) {
                            console.log('Initializing modal on demand');
                            try {
                                productModal = new bootstrap.Modal(modalElement, {
                                    backdrop: true,
                                    keyboard: true,
                                    focus: true
                                });
                            } catch (error) {
                                console.error('Failed to initialize modal:', error);
                                alert('页面加载错误，请刷新页面后重试');
                                return;
                            }
                        }

                        try {
                            console.log('Showing modal dialog');
                            productModal.show();
                        } catch (error) {
                            console.error('Failed to show modal:', error);
                            alert('显示编辑窗口失败，请刷新页面后重试');
                        }
                    },
                    error: function(jqXHR, textStatus, errorThrown) {
                        console.error('Failed to fetch product data:', {
                            status: jqXHR.status,
                            textStatus: textStatus,
                            errorThrown: errorThrown,
                            responseText: jqXHR.responseText
                        });
                        alert('获取产品信息失败: ' + textStatus);
                    }
                });
            }

            function deleteProduct(productId, productName) {
                if (confirm('确定要删除农产品 "' + productName + '" 吗？此操作不可恢复！')) {
                    const baseUrl = /*[[@{/admin/products}]]*/ '';
                    const url = `${baseUrl}/${productId}`;
                    console.log('Deleting product:', { id: productId, name: productName, url: url });

                    // 使用 POST 请求模拟 DELETE
                    $.ajax({
                        url: url,
                        type: 'POST',
                        data: { _method: 'DELETE' },
                        success: function(response) {
                            console.log('Delete response:', response);
                            if (response === 'success') {
                                location.reload();
                            } else {
                                console.error('Delete failed:', response);
                                alert('删除失败: ' + response);
                            }
                        },
                        error: function(jqXHR, textStatus, errorThrown) {
                            console.error('Delete request failed:', {
                                status: jqXHR.status,
                                textStatus: textStatus,
                                errorThrown: errorThrown,
                                responseText: jqXHR.responseText
                            });
                            alert('删除失败: ' + (jqXHR.responseText || textStatus));
                        }
                    });
                }
            }

            function saveProductEdit() {
                var formData = new FormData();
                formData.append('id', $('#editProductId').val());
                formData.append('name', $('#editProductName').val());
                formData.append('description', $('#editProductDescription').val());
                formData.append('category', $('#editProductCategory').val());
                formData.append('price', $('#editProductPrice').val());
                formData.append('stock', $('#editProductStock').val());
                
                var imageFile = $('#editProductImage')[0].files[0];
                if (imageFile) {
                    formData.append('imageFile', imageFile);
                }

                $.ajax({
                    url: /*[[@{/admin/products/update}]]*/ '',
                    type: 'POST',
                    data: formData,
                    processData: false,
                    contentType: false,
                    success: function(response) {
                        if (response === 'success') {
                            if (productModal) {
                                productModal.hide();
                            }
                            location.reload();
                        } else {
                            alert('保存失败: ' + response);
                        }
                    },
                    error: function() {
                        alert('保存失败');
                    }
                });
            }

            // 页面加载完成后的初始化
            $(document).ready(function() {
                console.log('Document ready, initializing...');
                
                // 确保 Bootstrap 已加载
                if (typeof bootstrap === 'undefined') {
                    console.error('Bootstrap is not loaded!');
                    return;
                }
                
                // 初始化模态框
                const modalElement = document.getElementById('editProductModal');
                if (modalElement) {
                    console.log('Initializing modal dialog');
                    try {
                        productModal = new bootstrap.Modal(modalElement, {
                            backdrop: true,
                            keyboard: true,
                            focus: true
                        });
                        console.log('Modal initialized successfully');
                    } catch (error) {
                        console.error('Failed to initialize modal:', error);
                    }
                } else {
                    console.error('Modal element not found during initialization');
                }

                // 审核按钮点击事件
                $('.approve-btn').click(function() {
                    var btn = $(this);
                    var productId = btn.data('product-id');
                    
                    if (confirm('确定要通过这个农产品的审核吗？')) {
                        $.post(/*[[@{/admin/products/}]]*/ '' + productId + '/approve')
                            .done(function(response) {
                                if (response === 'success') {
                                    location.reload();
                                } else {
                                    alert('操作失败: ' + response);
                                }
                            })
                            .fail(function() {
                                alert('操作失败');
                            });
                    }
                });

                // 监听模态框关闭事件
                if (modalElement) {
                    modalElement.addEventListener('hidden.bs.modal', function () {
                        console.log('Modal hidden, resetting form');
                        $('#editProductForm').trigger('reset');
                        $('#currentProductImage').empty();
                    });
                }
            });
        </script>
    </th:block>
</body>
</html> 